package com.security;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwsHeader;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.SigningKeyResolver;
import io.jsonwebtoken.security.Keys;

import java.security.Key;
import java.util.Map;

/**
 * 该类⽤于为每个⽤⼾提供单独的SecretKey(密钥)，同时在jws的解析过程中为jjwt查询用户的密钥
 */
public class CustomSigningKeyResolver implements SigningKeyResolver {
    Map<String, Key> secretKeyMap;
    Key defaultKey = Keys.secretKeyFor(SignatureAlgorithm.HS256);

    public CustomSigningKeyResolver(Map<String, Key> keyMap) {
        this.secretKeyMap = keyMap;
    }

    public Key lookupVerificationKey(String keyId) {
        if (this.secretKeyMap.containsKey(keyId)) return this.secretKeyMap.get(keyId);
        return defaultKey;
    }

    @Override
    public Key resolveSigningKey(JwsHeader header, Claims claims) {
        String keyId = header.getKeyId(); //or any other field that you need to in
        Key key = lookupVerificationKey(keyId); //implement me
        return key;
    }

    @Override
    public Key resolveSigningKey(JwsHeader header, String plaintext) {
        return resolveSigningKey(header, (Claims) null);
    }
}
